package com.ljl.question4;

import com.alibaba.fastjson.JSONObject;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.nio.charset.StandardCharsets;
import java.util.Locale;
import java.util.UUID;
import java.util.concurrent.Executors;

/**
 * mqtt客户端
 *
 * @author 20664
 */
public class PahoMqttClient {
    public static void main(String[] args) {
        String broker = "tcp://broker.emqx.io:1883";
        String clientId = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase(Locale.ENGLISH);
        MemoryPersistence persistence = new MemoryPersistence();
        try {
            MqttClient client = new MqttClient(broker, clientId, persistence);
            MqttConnectOptions options = new MqttConnectOptions();
            options.setCleanSession(false);
            client.connect(options);
            // 定时发送心跳
            Executors.newSingleThreadExecutor().execute(() -> {
                while (true) {
                    JSONObject data = new JSONObject();
                    data.put("msg", "hello, world");
                    data.put("timestamp", System.currentTimeMillis());
                    String topic = "testHeartbeat";
                    MqttMessage message = new MqttMessage();
                    message.setPayload(data.toJSONString().getBytes(StandardCharsets.UTF_8));
                    message.setQos(0);
                    try {
                        client.publish(topic, message);
                        Thread.sleep(1000); // Delay for 1 second
                    } catch (MqttException | InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
}
